﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System.Security.Claims;
using Zhao.Common.Applet;
using Zhao.Common.Helper;
using Zhao.IServer;
using Zhao.IServer.Field;
using Zhao.IServer.User;
using Zhao.Models.AppletDto;
using Zhao.Models.Entity;

namespace Zhao.Arena.MiniProgram.Api.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class OrdesController : ControllerBase
    {
        private readonly WechatAPIClient _wechatAPIClient;
        private readonly IUsersServer _usersServer;
        private readonly IOrdersServer _ordersServer;
        private readonly IAppointmentsServer _appointmentsServer;

        public OrdesController(WechatAPIClient wechatAPIClient, IUsersServer usersServer,IOrdersServer ordersServer, IAppointmentsServer appointmentsServer)
        {
            this._wechatAPIClient = wechatAPIClient;
            this._usersServer = usersServer;
            this._ordersServer = ordersServer;
            this._appointmentsServer = appointmentsServer;
        }


        /// <summary>
        /// 获取订单详情
        /// </summary>
        /// <param name="orderId">订单ID</param>
        /// <returns>订单详情</returns>
        [HttpGet("order-detail/{orderId}")]
        [Authorize]
        public async Task<JsonResult> GetOrderDetail(int orderId)
        {
            // 1. 获取当前用户ID
            string? idClaim = User?.Claims?.FirstOrDefault(c => c.Type.Equals(ClaimTypes.Sid))?.Value;
            if (idClaim.IsNullOrWhiteSpace())
            {
                return new JsonResult(new ApiResult<OrderDetailDto>
                {
                    Success = false,
                    Message = "无权限，请登录",
                    Data = null
                });
            }
            int userId = (int)idClaim.ToInt32();

            // 2. 验证请求参数
            if (orderId <= 0)
            {
                return new JsonResult(new ApiResult<OrderDetailDto>
                {
                    Success = false,
                    Message = "请提供有效的订单ID",
                    Data = null
                });
            }

            // 3. 调用服务层方法获取订单详情
            var result = await _ordersServer.GetOrderDetail(userId, orderId);
            return new JsonResult(result);
        }

        /// <summary>
        /// 获取活动订单详情
        /// </summary>
        /// <param name="orderId">订单ID</param>
        /// <returns>活动订单详情</returns>
        [HttpGet("activity-order-detail/{orderId}")]
        [Authorize]
        public async Task<JsonResult> GetActivityOrderDetail(int orderId)
        {
            // 1. 获取当前用户ID
            string? idClaim = User?.Claims?.FirstOrDefault(c => c.Type.Equals(ClaimTypes.Sid))?.Value;
            if (idClaim.IsNullOrWhiteSpace())
            {
                return new JsonResult(new ApiResult<ActivityOrderDetailDto>
                {
                    Success = false,
                    Message = "无权限，请登录",
                    Data = null
                });
            }
            int userId = (int)idClaim.ToInt32();

            // 2. 验证请求参数
            if (orderId <= 0)
            {
                return new JsonResult(new ApiResult<ActivityOrderDetailDto>
                {
                    Success = false,
                    Message = "请提供有效的订单ID",
                    Data = null
                });
            }

            // 3. 调用服务层方法获取活动订单详情
            var result = await _ordersServer.GetActivityOrderDetail(userId, orderId);
            return new JsonResult(result);
        }

        /// <summary>
        /// 智能获取订单详情（根据订单类型自动判断并返回相应的订单详情）
        /// </summary>
        /// <param name="orderId">订单ID</param>
        /// <returns>订单详情（可能是场馆预约订单或活动订单）</returns>
        [HttpGet("smart-order-detail/{orderId}")]
        [Authorize]
        public async Task<JsonResult> GetSmartOrderDetail(int orderId)
        {
            // 1. 获取当前用户ID
            string? idClaim = User?.Claims?.FirstOrDefault(c => c.Type.Equals(ClaimTypes.Sid))?.Value;
            if (idClaim.IsNullOrWhiteSpace())
            {
                return new JsonResult(new ApiResult<object>
                {
                    Success = false,
                    Message = "无权限，请登录",
                    Data = null
                });
            }
            int userId = (int)idClaim.ToInt32();

            // 2. 验证请求参数
            if (orderId <= 0)
            {
                return new JsonResult(new ApiResult<object>
                {
                    Success = false,
                    Message = "请提供有效的订单ID",
                    Data = null
                });
            }

            // 3. 先查询订单基本信息，确定订单类型
            var order = await _ordersServer.QueryAsync(o => o.OrderID == orderId && o.UserId == userId);
            if (order == null)
            {
                return new JsonResult(new ApiResult<object>
                {
                    Success = false,
                    Message = "未找到指定的订单或您没有权限查看该订单",
                    Data = null
                });
            }

            // 4. 根据订单类型调用不同的详情接口
            if (order.TypeId == 5 || order.TypeId == 11) // 5-活动支付，11-订单补购
            {
                var activityResult = await _ordersServer.GetActivityOrderDetail(userId, orderId);
                return new JsonResult(activityResult);
            }
            else if (order.TypeId == 7) // 7-场地预定
            {
                var appointmentResult = await _ordersServer.GetOrderDetail(userId, orderId);
                return new JsonResult(appointmentResult);
            }
            else
            {
                // 其他类型订单，暂时返回基本信息
                return new JsonResult(new ApiResult<object>
                {
                    Success = true,
                    Message = "该订单类型暂不支持详细查看",
                    Data = new
                    {
                        OrderId = order.OrderID,
                        TotalAmount = order.TotalAmount,
                        PaymentMethod = order.PaymentMethod,
                        PaymentTime = order.PaymentTime,
                        CreatedAt = order.CreatedAt,
                        Status = order.Status,
                        TypeId = order.TypeId,
                        TypeName = order.TypeId switch
                        {
                            1 => "充值",
                            3 => "提现",
                            5 => "活动支付",
                            7 => "场地预定",
                            9 => "订单取消退款",
                            10 => "部分退款",
                            11 => "订单补购",
                            _ => "未知类型"
                        }
                    }
                });
            }
        }

        /// <summary>
        /// 根据用户id查询相关账单
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="status">订单类型，0全部，3收入，5支出</param>
        /// <returns></returns>
        [HttpGet]
        [Route("{pageIndex:int}/{pageSize:int}")]
        [Route("{pageIndex:int}/{pageSize:int}/{status:int}")]
        [Authorize]
        public async Task<JsonResult> GetUserOrderDetails(int pageIndex = 1, int pageSize = 10, int status = 0)
        {
            PageModel<OrderByUserIdInfoDto> result = new PageModel<OrderByUserIdInfoDto>();

            Expressionable<Orders> expressionable = new Expressionable<Orders>();

            string? idClaim = User?.Claims?.FirstOrDefault(c => c.Type.Equals(ClaimTypes.Sid))?.Value;

            //获取到id
            if (idClaim.IsNullOrWhiteSpace())
            {
                result.msg = "缺少参数";
                result.code = 400;
                return new JsonResult(result);
            }

            int id = (int)idClaim.ToInt32();

            expressionable.And(a => a.UserId.Equals(id));

            expressionable.AndIF(status == 3, a => a.TypeId == 1 || a.TypeId == 9 || a.TypeId == 10 || a.TypeId == 13);

            expressionable.AndIF(status == 5, a => a.TypeId == 3 || a.TypeId == 5 || a.TypeId == 7 || a.TypeId == 11 || a.TypeId == 15);

            result = await _ordersServer.GetUserOrderAsync(pageIndex, pageSize, expressionable.ToExpression());

            return new JsonResult(result);
        }

    }
}
